package com.pt25.base.util;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SpringUtil {
    @Resource
    private ApplicationContext applicationContext;

    /**
     * 动态注册 Bean 到 Spring 容器中
     *
     * @param beanName Bean 的名称
     * @param bean     Bean 的实例
     */
    public void registerBean(String beanName, Object bean) {
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        configurableApplicationContext.getBeanFactory().registerSingleton(beanName, bean);
    }

    /**
     * @param beanName Bean的名称
     */
    public Object getBeanByBeanName(String beanName) {
        try {
            return applicationContext.getBean(beanName);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
}
